﻿package list;

import common.Node;

public class 打印两个有序链表的公共部分 {

	public static void main(String[] args) {
		Node head0 = new Node(1);
		Node head1 = new Node(2);

		Node head2 = new Node(3);
		Node head3 = new Node(4);
		Node head5 = new Node(5);
		Node head4 = new Node(7);

		head3.next = head5;
		head2.next = head3;
		head1.next = head2;

		head3.next = head4;
		head2.next = head3;
		head0.next = head2;

		printCommonNode(head0, head1);
	}

	/**
	 * 给定两个有序链表的头指针head1和head2，打印这两个链表的公共部分
	 * 
	 * @param head1
	 * @param head2
	 */
	public static void printCommonNode(Node head1, Node head2) {
		while (head1 != null && head2 != null) {
			if (head1.value < head2.value) {
				// 此时，head1比较大，需要移动head2的指针
				head1 = head1.next;
			} else if (head1.value > head2.value) {
				// 此时，head2比较多大,head1的指针需要后移
				head2 = head2.next;
			} else {
				System.out.print(head1.value + " ");
				head1 = head1.next;
				head2 = head2.next;
			}
		}

	}

}
